package com.sleepcamel.rest.domain.filegenerator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.sleepcamel.rest.domain.Mapping;
import com.sleepcamel.rest.domain.sourcegenerator.MappingSourceGenerator;
import com.sleepcamel.rest.domain.util.MiscUtils;

public class MappingFileGenerator implements IProjectFileGenerator{

	private File projectDirectory;
	private Mapping mapping;
	private MappingSourceGenerator mappingGenerator;

	public MappingFileGenerator(File projectDirectory) {
		this.projectDirectory = projectDirectory;
		this.mappingGenerator = new MappingSourceGenerator();
	}

	public void setMapping(Mapping mapping) {
		this.mapping = mapping;
		mappingGenerator.setData(mapping);
	}

	public void generate() throws IOException {
		// Do the magic
		File mappingDirectory = new File(projectDirectory, MiscUtils.packageToFilePath(mapping.getPackageName()));
		mappingDirectory.mkdirs();
		
		File interfaceFile = new File(mappingDirectory,"I"+mapping.getSourceClassName());
		writeCodeToFile(mappingGenerator.generateInterfaceSource(),interfaceFile);
		
		File classFile = new File(mappingDirectory,mapping.getSourceClassName());
		writeCodeToFile(mappingGenerator.generateClassSource(),classFile);
	}
	
	private void writeCodeToFile(String generatedCode, File codeFile) throws IOException {
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(codeFile));
		bufferedWriter.write(generatedCode);
		bufferedWriter.close();
	}

}
